import React, { Component } from "react";
import TodoItem from "./TodoItem";
import Footer from "./Footer";
import {todoGet,todoPost,todoPut,todoDel,todoBatchCheck} from '../api/todo'
import "./main.css";
export default class TodoCont extends Component {
  constructor() {
    super();
    this.state = {
      task: "",
      todolist: [
        // { objectId: Math.random(), taskname: "吃饭", ischeck: true },
        // { objectId: Math.random(), taskname: "睡觉", ischeck: true },
        // { objectId: Math.random(), taskname: "写代码", ischeck: false },
      ],
      tabIdx:0
    };
  }
  componentDidMount(){
    todoGet().then(res=>{
      console.log(res);
      this.setState({todolist:res.data.results})
    })
  }
  handleChange = (ev) => {
    //实现任务输入框与task的双向绑定
    this.setState({
      task: ev.target.value,
    });
  };
  handleSend = (ev) => {
    //任务新增
    let { task, todolist } = this.state;
    if (ev.keyCode === 13 && task.trim() !== "") {
      let taskObj = {
        taskname: task,
        ischeck: false,
      }
      todoPost(taskObj).then(res=>{
        console.log(res);
        taskObj.objectId = res.data.objectId  //将数据库下发的id，给到本地数据包
        todolist.push(taskObj);
        this.setState({ todolist, task: "" });
      })
    }
  };
  handleCheck = (objectId) => {
    //单选
    console.log(objectId);
    let { todolist } = this.state;
    let bool
    for(let i=0;i<todolist.length;i++){
      if(todolist[i].objectId===objectId){
        bool = !todolist[i].ischeck;
        todolist[i].ischeck = bool
        break
      }
    }
    todoPut(objectId,{ischeck:bool}).then(res=>{
      this.setState({ todolist });
    })
    
  };
  handleAllCheck = () => {
    //全选控制单选
    let { allCheck } = this.allInfo(); //原本的全选状态
    let { todolist } = this.state;
    todoBatchCheck(allCheck,todolist).then(res=>{
      todolist.forEach((item) => {
        item.ischeck = !allCheck;
      });
      this.setState({ todolist });
    })
  };
  handleDel = (objectId) => {
    //删除单个任务
    let { todolist } = this.state;
    todoDel(objectId).then(res=>{ //删除线上
      for(let i=0;i<todolist.length;i++){
        if(todolist[i].objectId===objectId){
          todolist.splice(i, 1);
          break
        }
      }
      this.setState({ todolist });
    })
  };
  handleUpdate = (objectId, newTaskName) => {
    //编辑任务
    let { todolist } = this.state;
    todoPut(objectId,{taskname:newTaskName}).then(res=>{
      for(let i=0;i<todolist.length;i++){
        if(todolist[i].objectId===objectId){
          todolist[i].taskname = newTaskName;
          break
        }
      }
      this.setState({ todolist });
    })
  };
  handleDelComplete = ()=>{ //删除已完成
    let {todolist} = this.state
    // 正向删除
    // for(let i=0;i<todolist.length;i++){
    //   if(todolist[i].ischeck){
    //     todolist.splice(i,1)
    //     i--
    //   }
    // }
    // 逆向删除
    for(let i=todolist.length-1;i>=0;i--){
      if(todolist[i].ischeck){
        todolist.splice(i,1)
      }
    }
    this.setState({todolist})
  }
  handleTab = (tabIdx)=>{
    this.setState({tabIdx})
  }
  allInfo = () => {
    //根据每一条任务的状态，运算得到一个全选的状态
    let { todolist } = this.state;
    let allCheck = true; //假设为全选
    let leftNum = 0; //剩余任务数量
    let len = todolist.length;
    for (let i = 0; i < len; i++) {
      if (!todolist[i].ischeck) {
        allCheck = false;
        leftNum++;
      }
    }
    return { allCheck, leftNum };
  };
  filterTodoList = ()=>{  //根据tabIdx的变化，动态过滤符合条件的数据，并返回
    let {todolist,tabIdx} = this.state
    switch (tabIdx) {
      case 1:  //未完成
        return todolist.filter(item=>{
          return !item.ischeck
        })
      case 2:  //已完成
        return todolist.filter(item=>{
          return item.ischeck
        })
      default:  //所有
        return todolist
    }
  }
  render() {
    let { task, todolist,tabIdx } = this.state;
    let { allCheck, leftNum } = this.allInfo();
    console.log("TodoCont的render方法");
    return (
      <div className="cont">
        <header className="header">
          <h1>Todos</h1>
          <input
            type="text"
            className="new-todo"
            placeholder="请输入待办事项~"
            value={task}
            onChange={this.handleChange}
            onKeyUp={this.handleSend}
          />
        </header>

        <section className="main">
          <input
            type="checkbox"
            className="toggle-all"
            checked={allCheck}
            onChange={this.handleAllCheck}
          />
          <ul className="todo-list">
            {this.filterTodoList().map((item, index) => {
              // return <TodoItem taskname={item.taskname} ischeck={item.ischeck}/>
              return (
                <TodoItem
                  key={item.objectId}
                  {...item}
                  idx={index}
                  handleCheck={this.handleCheck}
                  handleDel={this.handleDel}
                  handleUpdate={this.handleUpdate}
                />
              );
            })}
          </ul>
        </section>

        {todolist.length ? (
          <Footer
            leftNum={leftNum}
            handleDelComplete={this.handleDelComplete}
            tabIdx={tabIdx}
            handleTab={this.handleTab}
          />
        ) : (
          ""
        )}
      </div>
    );
  }
}
